package com.example.springbootdemo.api

import com.example.springbootdemo.entity.Department
import com.example.springbootdemo.entity.Person
import com.example.springbootdemo.repository.DepartmentRepository
import com.example.springbootdemo.repository.PersonRepository
import org.springframework.data.repository.findByIdOrNull
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController

@RestController
@RequestMapping("/departments")
class DepartmentApi(
        val departmentRepository: DepartmentRepository,
        val personRepository: PersonRepository
) {
    @GetMapping("")
    fun getAll() = departmentRepository.findAll()

    @GetMapping("/{id}")
    fun get(@PathVariable id: Long) = departmentRepository.findByIdOrNull(id)

    @GetMapping("/addTest")
    fun addTest() = departmentRepository.saveAll(
            listOf(
                    Department(1, "研發部"),
                    Department(2, "設計部")
            )
    )

    @GetMapping("{department_id}/addPerson/{person_id}")
    fun addPerson(
            @PathVariable department_id: Long,
            @PathVariable person_id: Long
    ): Person? {
        val person = personRepository.findByIdOrNull(person_id) ?: return null
        val department = departmentRepository.findByIdOrNull(department_id) ?: return null
        department.personSet.add(person)
        person.department = department
        departmentRepository.saveAndFlush(department)
        return personRepository.save(person)
    }
}